#include <bits/stdc++.h>
#define startt ios_base::sync_with_stdio(false);cin.tie(0);
typedef long long ll;
using namespace std;
#define vint vector<int>
#define all(v) v.begin(), v.end()
#define MOD 1000000007 //1e9+7
#define MOD2 998244353
#define MX 1000000000 //1e9
#define MXL 1000000000000000000
#define PI (ld)2*acos(0.0)
#define pb push_back
#define sc second
#define fr first
#define inte long long
#define ld long doublelu
int main()
{
// 1 1
// 3 -1 -2 -3
startt
ll x,k;
cin>>x>>k;
vector<pair<ll,ll>> b;
while(k--){
int y;
cin>>y;
int d=1;
ll j=0,m=0;
vector<ll> v;
// cout<<"yes"<<" ";
for(int i=0;i<y;i++){
ll a;
cin>>a;
if(a>=0 and d)x+=a;
else{
d=0;
j+=a;
v.pb(j);
// cout<<j<<" ";
}
}
int n=v.size();
if(n>1){
vector<pair<ll,ll>> c;
for(int i=0;i<n;i++){
m=min(m,v[i]);
if(v[i]>0){
c.pb({m,v[i]});
// cout<<m<<" "<<v[i]<<" ";
}
}
n=c.size();
if(n>0){
sort(c.rbegin(), c.rend());
b.pb({c[0].first,c[0].second});
ll st=c[0].second;
for(int i=0;i<n;i++){
if(c[i].second>st){
b.pb({c[i].first,c[i].second-st});
st=c[i].second;
// cout<<c[i].first<<" "<<c[i].second<<" ";
}
}
}
}
}
sort(b.rbegin(), b.rend());
for(auto it: b){
if(abs(it.first)<=x){
x+=it.second;
}
else break;
}
cout<<x<<endl;
return 0;
}
260C - Balls and Boxes | 1554A - Cherry |
11B - Jumping Jack | 716A - Crazy Computer |
644A - Parliament of Berland | 1657C - Bracket Sequence Deletion |
1657B - XY Sequence | 1009A - Game Shopping |
1657A - Integer Moves | 230B - T-primes |
630A - Again Twenty Five | 1234D - Distinct Characters Queries |
1183A - Nearest Interesting Number | 1009E - Intercity Travelling |
1637B - MEX and Array | 224A - Parallelepiped |
964A - Splits | 1615A - Closing The Gap |
4C - Registration System | 1321A - Contest for Robots |
1451A - Subtract or Divide | 1B - Spreadsheet |
1177A - Digits Sequence (Easy Edition) | 1579A - Casimir's String Solitaire |
287B - Pipeline | 510A - Fox And Snake |
1520B - Ordinary Numbers | 1624A - Plus One on the Subset |
350A - TL | 1487A - Arena |